package com.photovoltaic.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.photovoltaic.auth.entity.Permission;
import com.photovoltaic.auth.entity.Role;
import com.photovoltaic.auth.entity.User;
import com.photovoltaic.auth.payload.response.ApiResponse;
import com.photovoltaic.auth.payload.response.PageResponse;
import com.photovoltaic.auth.payload.response.UserDetailsResponse;
import com.photovoltaic.auth.security.CurrentUser;
import com.photovoltaic.auth.security.UserPrincipal;
import com.photovoltaic.auth.service.PermissionService;
import com.photovoltaic.auth.service.RoleService;
import com.photovoltaic.auth.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/auth/admin")
@PreAuthorize("hasAuthority('user:manage')")
public class AdminController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    /**
     * 获取用户列表（分页）
     *
     * @param page     页码
     * @param size     每页大小
     * @param username 用户名（可选）
     * @return 用户列表
     */
    @GetMapping("/users")
    public ResponseEntity<PageResponse<UserDetailsResponse>> getUsers(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String username
    ) {
        // 创建分页对象
        Page<User> pageRequest = new Page<>(page, size);
        
        // 构建查询条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(username)) {
            queryWrapper.like(User::getUsername, username);
        }
        
        // 查询用户列表
        IPage<User> userPage = userService.page(pageRequest, queryWrapper);
        
        // 转换为详细响应对象
        List<UserDetailsResponse> userResponses = userPage.getRecords().stream()
                .map(user -> {
                    UserDetailsResponse response = new UserDetailsResponse();
                    response.setId(user.getId());
                    response.setUsername(user.getUsername());
                    response.setEmail(user.getEmail());
                    response.setRealName(user.getRealName());
                    response.setMobile(user.getMobile());
                    
                    // 获取用户角色
                    List<Role> roles = userService.getUserRoles(user.getId());
                    response.setRoles(roles.stream()
                            .map(Role::getRoleName)
                            .collect(Collectors.toList()));
                    
                    // 获取用户权限
                    List<Permission> permissions = userService.getUserPermissions(user.getId());
                    response.setPermissions(permissions.stream()
                            .map(Permission::getPermissionKey)
                            .collect(Collectors.toList()));
                    
                    return response;
                }).collect(Collectors.toList());
        
        // 构建分页响应
        PageResponse<UserDetailsResponse> response = new PageResponse<>();
        response.setContent(userResponses);
        response.setPageNumber(userPage.getCurrent());
        response.setPageSize(userPage.getSize());
        response.setTotalElements(userPage.getTotal());
        response.setTotalPages(userPage.getPages());
        
        return ResponseEntity.ok(response);
    }

    /**
     * 获取单个用户详情
     *
     * @param userId 用户ID
     * @return 用户详情
     */
    @GetMapping("/users/{userId}")
    public ResponseEntity<UserDetailsResponse> getUserById(@PathVariable Long userId) {
        User user = userService.getById(userId);
        if (user == null) {
            return ResponseEntity.notFound().build();
        }
        
        UserDetailsResponse response = new UserDetailsResponse();
        response.setId(user.getId());
        response.setUsername(user.getUsername());
        response.setEmail(user.getEmail());
        response.setRealName(user.getRealName());
        response.setMobile(user.getMobile());
        
        // 获取用户角色
        List<Role> roles = userService.getUserRoles(user.getId());
        response.setRoles(roles.stream()
                .map(Role::getRoleName)
                .collect(Collectors.toList()));
        
        // 获取用户权限
        List<Permission> permissions = userService.getUserPermissions(user.getId());
        response.setPermissions(permissions.stream()
                .map(Permission::getPermissionKey)
                .collect(Collectors.toList()));
        
        return ResponseEntity.ok(response);
    }

    /**
     * 更新用户权限
     *
     * @param userId   用户ID
     * @param request  权限请求体
     * @param principal 当前登录用户
     * @return 更新结果
     */
    @PutMapping("/users/{userId}/permissions")
    public ResponseEntity<ApiResponse> updateUserPermissions(
            @PathVariable Long userId,
            @RequestBody Map<String, List<String>> request,
            @CurrentUser UserPrincipal principal
    ) {
        // 检查用户是否存在
        User user = userService.getById(userId);
        if (user == null) {
            return ResponseEntity.notFound().build();
        }
        
        // 阻止修改 admin 用户的权限（如果当前用户不是 admin）
        String currentUsername = principal != null ? principal.getUsername() : null;
        if ("admin".equals(user.getUsername()) && !"admin".equals(currentUsername)) {
            return ResponseEntity.badRequest()
                    .body(new ApiResponse(false, "无法修改管理员用户的权限"));
        }
        
        // 从请求中获取权限列表
        List<String> permissionKeys = request.get("permissions");
        if (permissionKeys == null) {
            permissionKeys = new ArrayList<>();
        }
        
        // 更新用户权限
        boolean success = userService.updateUserPermissions(userId, permissionKeys);
        
        if (success) {
            return ResponseEntity.ok(new ApiResponse(true, "用户权限更新成功"));
        } else {
            return ResponseEntity.badRequest()
                    .body(new ApiResponse(false, "用户权限更新失败"));
        }
    }

    /**
     * 获取所有权限列表
     *
     * @return 权限列表
     */
    @GetMapping("/permissions")
    public ResponseEntity<List<Permission>> getAllPermissions() {
        List<Permission> permissions = permissionService.list();
        return ResponseEntity.ok(permissions);
    }

    /**
     * 获取所有角色列表
     *
     * @return 角色列表
     */
    @GetMapping("/roles")
    public ResponseEntity<List<Role>> getAllRoles() {
        List<Role> roles = roleService.list();
        return ResponseEntity.ok(roles);
    }
} 